//
//  DetailViewController.m
//  CatMusic
//
//  Created by dllo on 15/4/24.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "DetailViewController.h"
#import "NetWorkingTool.h"
#import "DetailTableViewCell.h"
#import "MusicPlayViewController.h"
#import "BaseModel.h"
#import "UMSocial.h"
#import "PlayerSingleton.h"
#import "MJRefresh.h"
#import "NightMode.h"
#import "MBProgressHUD.h"
#import "AFNetworkReachabilityManager.h"

#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height
@interface DetailViewController ()<UITableViewDataSource,UITableViewDelegate , UIActionSheetDelegate , UIAlertViewDelegate>
@property(nonatomic, retain)NSMutableArray *tableViewArray;
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)NSMutableArray *playModelArray;// 传值建的model数组
@property(nonatomic , assign)NSInteger number;
@property(nonatomic, copy)NSString *str;
@property(nonatomic, retain)DetailTableViewCell *cell;
@property (nonatomic, retain) MBProgressHUD *mbProView;
@property (nonatomic , retain)UIView *myView;
@property (nonatomic ,retain)UIImageView *imageView;
@property(nonatomic, assign)BOOL state;
@end

@implementation DetailViewController
- (void)dealloc
{
    [_imageView release];
    [_myView release];
    [_mbProView release];
    [_cell release];
    [_str release];
    [_playModelArray release];
    [_idNum release];
    [_tableViewArray release];
    [_tableView release];
    [super dealloc];
}


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.tableViewArray = [NSMutableArray array];
        self.playModelArray = [NSMutableArray array];
        self.state = YES;
  }
    return self;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    [self blockAsndGet];
    [self creatTableView];
    [self tableViewRefresh];
    [self createMbProView];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setLightDayModel) name:@"LightDayNSNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setNightDayModel) name:@"NightDayNSNotification" object:nil];
    
    
    
#pragma mark - 判断网络状态    AFN
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    
    // 2.设置网络状态改变后的处理
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了, 就会调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                NSLog(@"未知网络");
                break;
                
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                NSLog(@"没有网络(断网)");
                [self alertViewCancel];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                NSLog(@"手机自带网络");
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                NSLog(@"WIFI");
                [self blockAsndGet];
                
                break;
        }
    }];
    
    // 3.开始监控
    [mgr startMonitoring];

    [self animationImage];
}

- (void)alertViewCancel
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络断开连接" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil, nil];
    [alert show];
}


// 动画
- (void)animationImage
{
    self.myView = [[UIView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.myView.backgroundColor = [UIColor whiteColor];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH / 2 - 40, HEIGHT / 2 - 200, WIDTH / 375 * 160, HEIGHT / 667 * 40)];
    label.text = @"努力加载中....";
    [self.myView addSubview:label];
    [label release];
    [self.view addSubview:self.myView];
    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(WIDTH / 2 -80, HEIGHT / 2 - 80, WIDTH / 375 * 160, HEIGHT / 667 * 160)];
    [self.myView addSubview:self.imageView];
    NSMutableArray *imageArr = [NSMutableArray array];
    for (NSInteger i = 1; i < 56 ; i++) {
        NSString *imageName = [NSString stringWithFormat:@"a%ld.png" , (long)i];
        UIImage *image = [UIImage imageNamed:imageName];
        [imageArr addObject:image];
    }
    self.imageView.animationImages = imageArr;
    self.imageView.animationDuration = 2.5;
    [self.imageView startAnimating];
    [_imageView release];
}








- (void)tableViewRefresh
{
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
       
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.tableViewArray removeAllObjects];
            [self blockAsndGet];
            [self.tableView reloadData];
            [self.tableView.header endRefreshing];
        });

        
    }];
    

    [self.tableView addLegendFooterWithRefreshingBlock:^{
        
        if (self.state == YES) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"已经最后啦" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
            
            [alert show];
            
            if (alert) {
                [alert dismissWithClickedButtonIndex:[alert cancelButtonIndex] animated:YES];
                [alert release];
            }
            
            self.state = NO;

        }
        
        [self.tableView.footer endRefreshing];
    }];

   
    
    
    
}


- (void)blockAsndGet
{
    
    NSString *str = [NSString stringWithFormat:@"http://api.dongting.com/channel/ranklist/%@/songs?page=1&app=ttpod&v=v7.9.0.2015032618&uid=&mid=iPhone4S&f=f320&s=s310&imsi=&hid=4B0F54AF4D21&splus=5.1.1&active=1&net=2&openudid=d3f55133770025ed5e9b00d0f8a0d477137d44ce&idfa=&utdid=Uh6TqwnEHHIDAAJyziZDt9mr&alf=201200", self.idNum];
    [NetWorkingTool netWorkingToolStr:str block:^(id result) {
        NSMutableDictionary *dic = result;
        NSMutableArray *dataArray = [dic objectForKey:@"data"];
        for (NSMutableDictionary *dic in dataArray) {
            BaseModel *playModel = [[[BaseModel alloc] init] autorelease];
            // 下面这一部分是为了给model赋值
            playModel.singer_name = [dic objectForKey:@"singerName"];
            playModel.song_name = [dic objectForKey:@"name"];
            NSMutableDictionary *mvListDictionary = [[dic objectForKey:@"mvList"] lastObject];
            playModel.pic_url = [mvListDictionary objectForKey:@"picUrl"];

            NSMutableArray *audition = [dic objectForKey:@"auditionList"];
            NSMutableDictionary *dic1 = [audition lastObject];
           playModel.songe_url = [dic1 objectForKey:@"url"];
//        self.playModel.song_time = [dic1 objectForKey:@"duration"];
            [self.playModelArray addObject:playModel];
            [self.tableViewArray addObject:dic];
        }
         [self.tableView reloadData];
        [_mbProView hide:YES];
    }];
}

- (void)createMbProView
{
    // 初始化
    self.mbProView = [[[MBProgressHUD alloc] initWithView:self.view] autorelease];
    
    [self.view bringSubviewToFront:self.mbProView];
    
    [_mbProView show:YES];
    _mbProView.labelFont = [UIFont systemFontOfSize:13];
    // 样式 圆形进度条
    //    _mbProView.mode = MBProgressHUDModeCustomView;
    _mbProView.mode = MBProgressHUDModeIndeterminate;
    
    _mbProView.labelText = @"努力加载中~";
    [self.view addSubview:_mbProView];
    
    
}



- (void)creatTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 25)];
    [self.tableView setDataSource:self];
    [self.tableView setDelegate:self];
    [self.tableView registerClass:[DetailTableViewCell class] forCellReuseIdentifier:@"cell"];
    self.tableView.rowHeight = 60;
    [self.view addSubview:self.tableView];
    [self.tableView release];
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tableViewArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ([NightMode shareNightMode].isNight) {
        [self setNightDayModel];
    } else {
        [self setLightDayModel];
    }

    
        self.cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    NSMutableDictionary *dic = self.tableViewArray[indexPath.row];
    self.cell.numberLabel.text = [NSString stringWithFormat:@"%ld", indexPath.row + 1];
    self.cell.songNameLabel.text = [dic objectForKey:@"name"];
    self.cell.singerLabel.text = [dic objectForKey:@"singerName"];
    self.cell.myButton.tag = indexPath.row + 1000;
    [self.cell.myButton addTarget:self action:@selector(cellMyButtonAction:andIndexPath:) forControlEvents:UIControlEventTouchUpInside];
    [self.myView removeFromSuperview];
    return self.cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MusicPlayViewController *musicPlay = [[MusicPlayViewController alloc] init];
    musicPlay.modelArr = self.playModelArray;
    musicPlay.indexPath = indexPath.row;
//    [self.navigationController presentViewController:musicPlay animated:YES completion:nil];
    [self.navigationController pushViewController:musicPlay animated:YES];
    [musicPlay release];

}

- (void)cellMyButtonAction:(UIButton *)button andIndexPath:(NSIndexPath *)index
{
    self.number = button.tag - 1000;
        UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"列表" delegate:self cancelButtonTitle:@"Bye Bye" destructiveButtonTitle:@"继续" otherButtonTitles:@"收藏" , @"分享",@"清除缓存" , nil];
        [actionSheet showInView:self.view];
    [actionSheet release];

}


- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    
    NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *sandBoxPath = [sandBox lastObject];
    NSFileManager *bigFileManager = [NSFileManager defaultManager];
    NSString *bigFileManagerPath = [sandBoxPath stringByAppendingPathComponent:@"collect"];
    [bigFileManager createDirectoryAtPath:bigFileManagerPath withIntermediateDirectories:YES attributes:nil error:nil];
    NSString *songName =  [self.playModelArray[self.number] song_name];
    NSString *songNameEncoding = [songName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    if (buttonIndex == 0) {
        NSLog(@"0");
    }
    else if (buttonIndex == 1){
        
            NSString *playModelPath = [bigFileManagerPath stringByAppendingFormat:@"/%@.plist" , songNameEncoding];
            [NSKeyedArchiver archiveRootObject:self.playModelArray[self.number] toFile:playModelPath];
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"收藏成功" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:nil, nil];
            [alert show];
       
    }
    else if (buttonIndex == 2){
        //注意：分享到微信好友、微信朋友圈、微信收藏、QQ空间、QQ好友、来往好友、来往朋友圈、易信好友、易信朋友圈、Facebook、Twitter、Instagram等平台需要参考各自的集成方法
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:@"5541c88ce0f55a9452003a17"
                                          shareText:@"分享来自CatMusic:"
                                         shareImage:[UIImage imageNamed:@"icon.png"]
                                    shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToDouban,nil]
                                           delegate:nil];

    }
    else if (buttonIndex == 3){
//        BOOL result = [bigFileManager removeItemAtPath:bigFileManagerPath error:nil];
        BOOL result = 1;
        if (result == 1) {
            UIAlertView *clearCaches = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定清除缓存???" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
            [clearCaches show];
            [clearCaches release];
        }else{
            NSLog(@"删除失败");
        }
    }
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        
        [self clearButton];
    }
}

- (void)clearButton
{
    //    UIButton *button = (UIButton *)sender;
    //    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    //    [button setTitle:@"正在清理中..." forState:UIControlStateNormal];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *path = [paths lastObject];
    
    //    NSString *str = [NSString stringWithFormat:@"缓存已清除%.1fM", [self folderSizeAtPath:path]];
    
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:path];
    for (NSString *p in files) {
        NSError *error;
        NSString *Path = [path stringByAppendingPathComponent:p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:Path]) {
            [[NSFileManager defaultManager] removeItemAtPath:Path error:&error];
        }
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"缓存已清除" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
    [alert release];
    
}



#warning 删除缓存
//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
//{
//    NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//    NSString *sandBoxPath = [sandBox lastObject];
//    NSFileManager *bigFileManager = [NSFileManager defaultManager];
//    NSString *bigFileManagerPath = [sandBoxPath stringByAppendingPathComponent:@"collect"];
//    [bigFileManager createDirectoryAtPath:bigFileManagerPath withIntermediateDirectories:YES attributes:nil error:nil];
//    
//    
//    NSFileManager *fileManager = [NSFileManager defaultManager];
//    NSString *singerName =  [self.playModelArray[self.number] song_name];
//    NSString *fileManagerPath = [bigFileManagerPath stringByAppendingPathComponent:singerName] ;
//    [fileManager createDirectoryAtPath:fileManagerPath withIntermediateDirectories:YES attributes:nil error:nil];
//    if (buttonIndex == 1) {
//        BOOL result = [bigFileManager removeItemAtPath:bigFileManagerPath error:nil];
//        if (result) {
//            NSLog(@"删除成功");
//        }else{
//            NSLog(@"删除失败");
//        }
//    }
//}


- (void)setLightDayModel
{
    
    self.tabBarController.tabBar.barTintColor = [UIColor colorWithRed:245 / 255.0 green:241/ 255.0 blue:143 / 255.0 alpha:1];//////
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:245 / 255.0 green:241/ 255.0 blue:143 / 255.0 alpha:1];//////
    
    //    self.tableView.backgroundColor = [UIColor whiteColor];
    self.cell.backgroundColor = [UIColor whiteColor];
//    self.cell.numberLabel.textColor = [UIColor purpleColor];
//    self.cell.singerLabel.textColor = [UIColor purpleColor];
//    self.cell.songNameLabel.textColor = [UIColor purpleColor];
    
    UIColor * color = [UIColor blackColor];
    //这里我们设置的是颜色，还可以设置shadow等，具体可以参见api
    NSDictionary * dict = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    //大功告成
    self.navigationController.navigationBar.titleTextAttributes = dict;
    
    
}

- (void)setNightDayModel
{
    
    self.tabBarController.tabBar.barTintColor = [UIColor blackColor];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:38 / 255.0 green:38/ 255.0 blue:38 / 255.0 alpha:1];

    //    self.tableView.backgroundColor = [UIColor grayColor];
    self.cell.backgroundColor = [UIColor colorWithRed:38 / 255.0 green:38/ 255.0 blue:38 / 255.0 alpha:1];
//    self.cell.numberLabel.textColor = [UIColor whiteColor];
//    self.cell.singerLabel.textColor = [UIColor whiteColor];
//    self.cell.songNameLabel.textColor = [UIColor whiteColor];
    
    UIColor * color = [UIColor whiteColor];
    //这里我们设置的是颜色，还可以设置shadow等，具体可以参见api
    NSDictionary * dict = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    //大功告成
    self.navigationController.navigationBar.titleTextAttributes = dict;

    
    
    
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
